<?php

namespace App\Jobs;

use App\Exceptions\ServiceException;
use App\Models\Game\ActEventList;
use App\Utils\MyLog;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;


class PushNotification implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $assembledData;
    private $pushUrl;
    private $gamearea;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($assembledData, $pushUrl,$gamearea)
    {
        $this->assembledData = $assembledData;
        $this->pushUrl = $pushUrl;
        $this->gamearea = $gamearea;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        DB::beginTransaction();

        try {
        $response = Http::withHeaders(['Content-Type' => 'application/json'])
            ->post($this->pushUrl, $this->assembledData);
        $body = json_decode($response->body(),true);
        $RetCode = data_get($body,'RetCode');
        $AccuRcYmb = data_get($this->assembledData, 'ActData.TlAccu.AccuRcYmb');

            if ($RetCode == 0) {
            // 推送成功，执行成功逻辑
            // 推送失败，保存失败请求信息
            $failedPush = new ActEventList();
            $failedPush->pushUrl = $this->pushUrl;
            $failedPush->RoleId = $this->assembledData['RoleId'];
            $failedPush->ActType = $this->assembledData['ActType'];
            $failedPush->ActId = $this->assembledData['ActId'];
            $failedPush->server_id = $this->gamearea;
            $failedPush->AccuRcYmb = $AccuRcYmb;
            $failedPush->status = $RetCode;
            $failedPush->created_at = now();;
            $failedPush->save();

            $failedPush->save();
        } else {
            // 推送失败，保存失败请求信息
            $failedPush = new ActEventList();
            $failedPush->pushUrl = $this->pushUrl;
            $failedPush->RoleId = $this->assembledData['RoleId'];
            $failedPush->ActType = $this->assembledData['ActType'];
            $failedPush->ActId = $this->assembledData['ActId'];
            $failedPush->server_id = $this->gamearea;
            $failedPush->AccuRcYmb = $AccuRcYmb;
            $failedPush->status = $RetCode;
            $failedPush->created_at = now();;

            $failedPush->save();
        }
            DB::commit();

        } catch (\Exception $e) {
            // 请求异常，处理异常
            MyLog::error("请求异常：" . $e->getMessage());
            // 抛出异常，以便队列工作进程可以将任务标记为失败
            DB::rollback();

            throw $e;
        }
    }
}
